//帐号列表
let Accounts_Object = {
   "field": function(n,t){ return Apps.field("change_accounts", n, t); },
   "reload": function(){ this.list(); },
   "menu": function(e, i, r){
       e.preventDefault();//阻止浏览器自带的右键菜单弹出
       let m = $('#account_menu');

       let dats = $(this).datagrid("getSelections");
       if(dats.length < 1){ $(this).datagrid('selectRow',i); }

       if(m.children("div:not([class*='menu-line'])").length > 0){
          m.menu('show', {left:e.pageX, top:e.pageY, hideOnUnhover:false});
       }
   },
   "row_dbclick":function(rowIndex, rowData){ Accounts_Object.change(); },
   "list": function(page, limit){
          let dg = $("#acc_dg");
          let dat ={
              page: (page ? page : 0),
              limit: (limit ? limit : null)
          };
          Public_Object.search(dg, dat, {
              "api_url": window.Api.user.search,
              "callback":function(d){
                      d.forEach(function(v,i){
                              v.create_date = UnixToDateTime(v.create_date);
                              v.status_val= v.status ? '<font color=green>正常</font>' : '<font color=red>已禁用</font>';
                              let dat = Apps.data.role[v.role_id];
                              v.role_name = dat ? dat.role_name : '';
                      });
                      return d;
              }
          }, Accounts_Object.list);

/*
      dg.datagrid("loading"); //加屏蔽
      get_dats(window.Api.user.search,{},function(d, err){
           if(err){ Public_Object.alert("获取列表返回错误!"); return; }
           if(!d.status){Public_Object.alert(d.msg);}
           d.data.forEach(function(v,i){
                 v.create_date = UnixToDateTime(v.create_date);
                 v.status_val= v.status ? '<font color=green>正常</font>' : '<font color=red>已禁用</font>';
                 let dat = Apps.data.role[v.role_id];
                 v.role_name = dat ? dat.role_name : '';
           });
            //加载数据
           dg.datagrid('loadData',{"rows":d.data, total:d.total});  //记录总数
           dg.datagrid("loaded"); //移除屏蔽
      });
      */
   },
   "change": function(act){
      let node = $("#change_accounts");
      let obj = this.field(['real_name','user_name', 'password', 'create_date', 'role_id','status', 'note']);
      let row = null;
      $.each(obj, function(i,v){ v.val(''); });

      obj.role_id.find('option:not(:first-child)').remove();
      Object.keys(window.Apps.data.role).forEach(function(k,i){
             let v = window.Apps.data.role[k];
             obj.role_id.append('<option value="'+v.id+'">'+v.role_name+'</option>');
      });

      if(!act){
         //修改
         row = $("#acc_dg").datagrid("getSelected");
         if(!row) return;
         Object.keys(obj).forEach(function(k){ obj[k].val(row[k]); });
         obj.user_name.attr("readonly",true);
         obj.password.attr("placeholder",row.password.substr(0,23).replace(/(.)/g,'*'));
         obj.password.val('');
         obj.create_date.val(UnixToDateTime(row.create_date));
         obj.status[0].checked = row.status ? true : false;
      } else {
          obj.user_name.removeAttr("readonly");
          obj.password.attr("placeholder","");
      }

      let opt = Apps.dialog_opt();
      opt.title = act ? "新增帐号" : "修改帐号信息 ID: " + row.id;
      opt.buttons = [
         {text:"确认",iconCls :'icon-ok',handler:function(){
             let dats = {
                "id":act ? 0 : row.id,
                "user_name":obj.user_name.val(),
                "real_name":obj.real_name.val(),
                "role_id":obj.role_id.val(),
                "note":obj.note.val(),
                "status":(obj.status[0].checked ? 1 : 0)
             };
             if(obj.password.val().length) dats.password =  Crypt_hash(obj.password.val(),'md5');

             let api_url = window.Api.user.add;

             if(!act){
                  if(dats.user_name) delete dats.user_name;
                  api_url = window.Api.user.update;
             }
             get_dats(api_url, dats, function(d,err){
                     if(err){console.log(err); alert("保存出错!"); return;}
                     if(!d.status){Public_Object.alert(d.msg); return;}
                     //console.log(sql);
                     Accounts_Object.reload();
             });

   	      	node.dialog('close');
   	    }}, {text:"取消",iconCls :'icon-cancel',handler:function(){ node.dialog('close'); }}
      ];
      Apps.Dialog_Show(node, opt);
   },
   "del": function(){
      let row = $("#acc_dg").datagrid("getSelected");
      if(!row) return;
      Public_Object.confirm({content:'<p>您确定要删除 "'+row.id+'"</p>'}, function(){
          let ret = getByRsync(window.Api.user.del,{"id":row.id});
          if(!ret.status) Public_Object.alert(ret.msg);
          Accounts_Object.reload();
      });
   },
   "grants_list":function(row){
         let ids = row ? ',' + row.grants + ',' : '';
         console.log(ids);
         let grants = {
              "show": function(){
                     let data = this.children(window.Apps.data.grants);
                     return {"data":data};
              },
              "children":function(dat){
                     let ch = [];
                     dat.forEach(function(v,i){
                           let d = {"text":v.name};
                           if(v.id){
                                 d.id = v.id;
                                 if(!v.children && ids.indexOf(v.id) > -1) d.checked = true;
                           }
                           if(v.children){
                              d.state = "closed";
                              d.children = grants.children(v.children);
                           }
                            ch.push(d);
                     });
                     return ch;
              }
         };

         $('#role_tree').tree(grants.show());
   },
   "get_grants":function(){
         let ids = [];

         let grants = {
              "get": function(){
                    this.children($("#role_tree").tree("getRoots"));
              },
              "children":function(dat){
                     dat.forEach(function(v,i){
                           if(v.id && 'unchecked' != v.checkState) ids.push(v.id);
                           if(v.children) grants.children(v.children);
                     });
              }
         };

         grants.get();

         return ids;
   },
   //角色管理
   "role":function(){
        let node = $("#change_role");
        //let tab = $("#role_tabs");

        this.role_list();

        let opt = Apps.dialog_opt();
        opt.title = "角色列表 ";
        opt.buttons = [{text:"新增", iconCls:"icon-add",handler:function(){ Accounts_Object.add_role(); }},
        {text:"删除", iconCls:"icon-remove",handler:function(){ Accounts_Object.role_del(); }},
        {text:"关闭",iconCls :'icon-cancel',handler:function(){ node.dialog('close'); }}];
        Apps.Dialog_Show(node, opt);
   },
   "role_dbclick":function(rowIndex, rowData){Accounts_Object.add_role(rowData);},
   "role_list": function(){
         let dg = $("#role_dg");
         dg.datagrid("loading"); //加屏蔽
         get_dats(window.Api.role.search,{},function(d, err){
              if(err){ Public_Object.alert("获取列表返回错误!"); return; }
              if(!d.status){Public_Object.alert(d.msg);}
              d.data.forEach(function(v,i){
                    v.create_date = UnixToDateTime(v.create_date);
                    v.status_val= v.status ? '<font color=green>已启用</font>' : '<font color=red>已禁用</font>';
              });
               //加载数据
              dg.datagrid('loadData',{"rows":d.data, total:d.total});  //记录总数
              dg.datagrid("loaded"); //移除屏蔽
         });
   },
   "add_role":function(row){
         let dom = $("#change_role").find("#add_role");
         let obj = Apps.field(dom[0], ['role_name','status']);

         Accounts_Object.grants_list(row);

          dom.data("raw",null);

         $.each(obj, function(i,v){ v.val(''); });

         if(row){
                dom.data("raw",row);
                obj.role_name.val(row.role_name);
                obj.status[0].checked = row.status ? true : false;
          }

          dom.show();
   },
   //保存角色修改
   "save_role": function(){
           let dom = $("#add_role");
           let obj = Apps.field(dom[0], ['role_name','status']);
           let api_url = window.Api.role.add;
           let row = dom.data("raw");

           let dats = {
               "role_name":obj.role_name.val(),
               "status":obj.status[0].checked ? 1 : 0,
               "grants":Accounts_Object.get_grants().toString()
           };
           if(row){ //修改
                  dats.id = row.id;
                  api_url = window.Api.role.update;
           }

           get_dats(api_url,dats,function(d){
                  if(!d.status){
                       Public_Object.alert(d.msg);
                   }else{
                       window.Apps.data.role = JSON.parse(JSON.stringify(d.data));
                       Accounts_Object.role_list();
                       dom.hide();
                   }

           });
   },
   //删除角色
   "role_del": function(){
      let row = $("#role_dg").datagrid("getSelected");
      if(!row) return;
      Public_Object.confirm({content:'<p>您确定要删除 [ID:'+row.id+']  '+row.role_name+'</p>'}, function(){
          let ret = getByRsync(window.Api.role.del,{"id":row.id});
          if(!ret.status){
              Public_Object.alert(ret.msg);
          } else {
              window.Apps.data.role = JSON.parse(JSON.stringify(ret.data));
          }
          Accounts_Object.role_list();
      });
   },
}
